package com.william.lifetraxer;

import static com.william.lifetraxer.util.DbManager.*;

import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.Marshaller;

import com.william.lifetraxer.util.Info;
import com.william.lifetraxer.util.InfoDAO;
import static com.william.lifetraxer.util.Values.*;

public class InfoHandler extends HttpServlet {

	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		doPost(request,response);
	}

	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		request.setCharacterEncoding("UTF-8");
		response.setCharacterEncoding("UTF-8");
		response.setContentType("text/plain;charset=UTF-8");
		PrintWriter out = response.getWriter();
		
		String handleType = request.getParameter("info_handle_type");
		String username = request.getParameter("info_username");
		String gender = request.getParameter("info_gender");
		String birthday = request.getParameter("info_birthday");
		if("".equals(birthday)){
			birthday = "0000-00-00";
		}
		String phone = request.getParameter("info_phone");
		String email = request.getParameter("info_email");
		
		Info info ;
		int result = 0;
		
		if("insert_info".equals(handleType))
		{
			info = new Info(username,Integer.parseInt(gender), birthday, phone, email);
			
			result = InfoDAO.insertInfo(info);
			
			if(result==ADD_INFO_OK)
			{
				out.print("ADD_INFO_OK");
			}
			else if(result==USER_NOT_EXIST)
			{
				out.print("USER_NOT_EXIST");
			}
			else if(result==DATABASE_ERROR)
			{
				out.print("DATABASE_ERROR");
			}
		}
		else if("update_info".equals(handleType))
		{
			info = new Info(username,Integer.parseInt(gender), birthday, phone, email);
			result = InfoDAO.updateInfo(info);
			
			if(result==UPDATE_INFO_OK)
			{
				out.print("UPDATE_INFO_OK");
			}
			else if(result==USER_NOT_EXIST)
			{
				out.print("USER_NOT_EXIST");
			}
			else if(result==DATABASE_ERROR)
			{
				out.print("DATABASE_ERROR");
			}
		}
		else if("get_info".equals(handleType)&&username!=null)
		{
			info = InfoDAO.getInfo(username);
			String infoXml = getInfoXml(info);
			out.print(infoXml);
		}
		else
		{
			out.print("VALID_INFO_HANDLE_TYPE");
		}
		out.close();
	}

	private String getInfoXml(Info info)
	{
		StringWriter sw = null;
		try
		{
			sw = new StringWriter();
			JAXBContext context = JAXBContext.newInstance(Info.class);
			Marshaller m = context.createMarshaller();
			m.marshal(info, sw);
		}
		catch(Exception e)
		{
			e.printStackTrace();
			return null;
		}
		return sw.toString();
	}

}
